package com.yun.image.yunimagebackend.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yun.image.yunimagebackend.annotation.AuthCheck;
import com.yun.image.yunimagebackend.common.BaseResponse;
import com.yun.image.yunimagebackend.common.ResultUtils;
import com.yun.image.yunimagebackend.constant.UserConstant;
import com.yun.image.yunimagebackend.exception.ErrorCode;
import com.yun.image.yunimagebackend.exception.ThrowUtils;
import com.yun.image.yunimagebackend.model.dto.user.UserLoginRequest;
import com.yun.image.yunimagebackend.model.dto.user.UserQueryRequest;
import com.yun.image.yunimagebackend.model.dto.user.UserRegisterRequest;
import com.yun.image.yunimagebackend.model.entity.User;
import com.yun.image.yunimagebackend.model.vo.user.LoginUserVo;
import com.yun.image.yunimagebackend.model.vo.user.UserVO;
import com.yun.image.yunimagebackend.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Api(tags = "用户接口")
@RestController
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(userRegisterRequest), ErrorCode.PARAMS_ERROR);

        Long userId = userService.userRegister(userRegisterRequest.getUserAccount(), userRegisterRequest.getUserPassword(), userRegisterRequest.getCheckPassword());

        return ResultUtils.success(userId);
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public BaseResponse<LoginUserVo> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(userLoginRequest), ErrorCode.PARAMS_ERROR);

        LoginUserVo userVo = userService.userLogin(userLoginRequest.getUserAccount(), userLoginRequest.getUserPassword(), request);

        return ResultUtils.success(userVo);
    }

    /**
     * 获取当前登录用户
     */
    @ApiOperation("获取当前登录用户")
    @PostMapping("/get/login")
    public BaseResponse<LoginUserVo> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(BeanUtil.copyProperties(user, LoginUserVo.class));
    }

    @ApiOperation("用户注销")
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        userService.userLogout(request);
        return ResultUtils.success(true);
    }

    /**
     * 管理员创建用户
     */
    @ApiOperation("创建用户")
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody User user) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(user), ErrorCode.PARAMS_ERROR);
        //设置默认密码
        user.setUserPassword(userService.getEncryptPassword("123456"));
        boolean save = userService.save(user);
        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 管理员获取用户信息
     */
    @ApiOperation("获取用户信息")
    @PostMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUser(@RequestBody Long userId) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(userId), ErrorCode.PARAMS_ERROR);
        User user = userService.getById(userId);
        ThrowUtils.throwIf(ObjUtil.isEmpty(user), ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 获取脱敏后的用户数据
     */
    @ApiOperation("获取脱敏后的用户数据")
    @PostMapping("/get/vo")
    public BaseResponse<UserVO> getUserVo(long id) {
        User user = getUser(id).getData();
        UserVO userVo = BeanUtil.copyProperties(user, UserVO.class);
        return ResultUtils.success(userVo);
    }

    /**
     * 删除用户（仅管理员可操作）
     */
    @ApiOperation("删除用户")
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody long id) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(id), ErrorCode.PARAMS_ERROR);
        boolean b = userService.removeById(id);
        ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(b);
    }

    /**
     * 分页查询（管理员可操作）
     */
    @ApiOperation("分页查询")
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<User>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(userQueryRequest), ErrorCode.PARAMS_ERROR);
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(ObjUtil.isNotNull(userQueryRequest.getId()), User::getId, userQueryRequest.getId());
        qw.like(StrUtil.isNotBlank(userQueryRequest.getUserName()), User::getUserName, userQueryRequest.getUserName());
        qw.like(StrUtil.isNotBlank(userQueryRequest.getUserAccount()), User::getUserAccount, userQueryRequest.getUserAccount());
        qw.like(StrUtil.isNotBlank(userQueryRequest.getUserProfile()), User::getUserProfile, userQueryRequest.getUserProfile());
        Page<User> objectPage = new Page<>(userQueryRequest.getCurrent(), userQueryRequest.getPageSize());
        //拼接排序条件
        if (StrUtil.isNotBlank(userQueryRequest.getSortField())) {
            OrderItem orderItem = new OrderItem();
            orderItem.setAsc("asc".equals(userQueryRequest.getSortOrder()));
            orderItem.setColumn(userQueryRequest.getSortField());
            objectPage.addOrder(orderItem);
        }
        Page<User> userPage = userService.page(objectPage, qw);
        return ResultUtils.success(userPage);
    }

}
